
<template>
  <Card>

    <template #title>
      <div class="flex justify-content-between">
        <!-- @vue-ignore -->
        <Button label="新增" icon="pi pi-plus" iconPos="right" @click="dialogRef?.openDialog()" />
        <span class="p-input-icon-left flex">
          <i class="pi pi-search z-1" />
          <InputText v-model="filterUsername" placeholder="请输入username" />
        </span>
      </div>
    </template>
    <template #content>
      <!-- ! lazy 模式下 totalRecords 才能生效 -->
      <DataTable paginator @page="onPageChange" :rows="pageSize" :totalRecords="total"
        :rowsPerPageOptions="[5, 10, 20, 50]" lazy :loading="loading" :value="data" data-key="id"
        tableStyle="min-width: 50rem" columnResizeMode="expand">
        <Column field="username" header="用户名" class="w-5rem"></Column>
        <Column field="nickname" header="昵称" class="w-5rem"></Column>
        <Column field="mobile" header="手机号"></Column>
        <Column field="createAt" header="创建日期">
          <template #body="slotProps">
            {{ dayjs(slotProps.data.createdAt).format('YYYY/MM/DD HH:mm:ss') }}
          </template>
        </Column>
        <Column field="updatedAt" header="更新日期">
          <template #body="slotProps">
            {{ dayjs(slotProps.data.updatedAt).format('YYYY/MM/DD HH:mm:ss') }}
          </template>
        </Column>
        <Column field="isUsed" header="可用状态" class="w-6rem">
          <template #body="slotProps">
            <Tag :value="slotProps.data.isUsed == 1 ? '启用' : '禁用'" :severity="slotProps.data.isUsed == 1 ? 'success' : 'warning'" />
          </template>
        </Column>
        <Column field="isDeleted" header="在线状态" class="w-6rem">
          <template #body="slotProps">
            <Tag :value="slotProps.data.username == userStore.username ? '在线' : '离线'"
              :severity="slotProps.data.username == userStore.username ? 'success' : 'danger'" />
          </template>
        </Column>
        <Column field="operator" header="操作" class="w-14rem">
          <template #body="slotProps">
            <SplitButton label="菜单授权" icon="pi pi-plus" raised size="small" @click="updateAuth(slotProps.data)"
              :model="btnItems(slotProps.data)" />
          </template>
        </Column>
      </DataTable>
    </template>
  </Card>
  <AddAdmin ref="dialogRef" @reload="reload"/>
</template>

<script setup lang="ts">
import { ref, onMounted, getCurrentInstance } from 'vue';
import { } from 'primevue/api'
import dayjs from 'dayjs';
import { usePagination } from '@alova/scene-vue'
import { useToast, POSITION } from 'vue-toastification'
import { useRouter } from 'vue-router'
import { DataTable, Column, Card, Button, Tag, SplitButton, InputText } from '@/utils/primevue'
import { useAdminStore } from '@/stores/admin';
import { useUserStore } from '@/stores/user'
import type { TAdminInfo, TResponse } from '@/typing/base';
import AddAdmin from './components/AddAdmin.vue';
import { disabledAdmin, queryAdminList } from '@/api/admin';
import { string } from 'yup';

const toast = useToast()
const adminStore = useAdminStore()
const userStore = useUserStore()
const router = useRouter()
const dialogRef = ref(undefined)
const filterUsername = ref<string>('')
const app = getCurrentInstance()
const btnItems = (props: TAdminInfo) => {
  return [
    {
      label: props.isUsed == 1 ? '禁用' : '启用',
      icon: 'pi pi-unlock',
      command: async () => {
        console.log('禁用', props)
        adminStore.disabledAdmin({
          id: props.id,
          used: props.isUsed == 1 ? '-1' : '1'
        }, () => {
          toast.success("禁用/启用成功！");
          refresh()
        })
      }
    },
    {
      label: '重置密码',
      icon: 'pi pi-sliders-h',
      command: () => {
      }
    },
    {
      label: '下线',
      icon: 'pi pi-sign-out',
      command: () => {
      }
    },
    {
      label: '删除', icon: 'pi pi-power-off', command: async () => {
        adminStore.deleteAdmin({
          id: props.id,
        }, () => {
          toast.success("删除成功！");
          reload()
        })
      }
    }
  ]
};

// onMounted(() => {
//  adminStore.queryAdminList()
// });

const {
  // 重置表格数据，请求第一页
  reload,
  refresh,
  // 加载状态
  loading,
  // 列表数据
  data,
  // 当前页码，改变此页码将自动触发请求
  page,
  // 每页数据条数
  pageSize,
  // 总数据量
  total
} = usePagination(
  // Method实例获取函数，它将接收page和pageSize，并返回一个Method实例
  (page, pageSize) => queryAdminList({ page: page, pageSize, username: filterUsername.value }),
  {
    preloadPreviousPage: false, // 关闭预加载上一页数据
    preloadNextPage: false, // 关闭预加载下一页数据
    total: (res: any) => res.data.total,
    data: (res: any) => res.data.adminList as TAdminInfo[],
    // 请求前的初始数据（接口返回的数据格式）
    initialData: { total: 0, data: [] },
    initialPage: 1, // 初始页码，默认为1
    initialPageSize: 10, // 初始每页数据条数，默认为10
    watchingStates: [filterUsername],
    debounce: 500
  }
);

// 页码改变的事件处理函数
const onPageChange = (event: any) => {
  page.value = event.page + 1
  pageSize.value = event.rows
}

const updateAuth = (props: TAdminInfo) => {
  router.push({
    path: `/admin/auth/${props.id}`,
  })
}

</script>
